package com.tcl.aota.admin.job;

import com.tcl.aota.admin.dto.FileDTO;
import com.tcl.aota.admin.util.FileStoreUtil;
import com.tcl.aota.common.constants.Constants;
import com.tcl.aota.common.utils.DateUtil;
import com.tcl.aota.common.utils.JsonParser;
import com.tcl.aota.common.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.Date;

/**
 * @author kelong
 * @date 11/20/14
 */
public class UpFileJob {
    static Logger LOG = Logger.getLogger(UpFileJob.class);

    /**
     * Day job.
     * one step:again upload the failed file to amazons3
     * second step:clear the expired file.
     */
    public static void up() {
        try {
            //重命名文件
            LOG.info("job Start...");
            LOG.info("one step:again upload the file to amazons3....");
            File file = new File(Constants.Common.FAILURE_FILE_PATH);
            String descPath = "";
            if (file.exists()) {
                descPath = StringUtil.append(Constants.Common.FAILURE_FILE_PATH_HIS,
                    DateUtil.fomartDateToStr(Constants.Common.DATE_FORMART_2, new Date()),
                    ".log");
                file.renameTo(new File(descPath));
                againStoreS3(descPath);
            } else {
                LOG.info("file don't exists." + Constants.Common.FAILURE_FILE_PATH);
            }
            LOG.info("second step: clear the temp file....");
            String tmpDir = FileStoreUtil.getUploadTempDir();
            File tmpDirFile = new File(tmpDir);
            clearTempFile(tmpDirFile);
            int expireCount = UpFileInstance.getInstance().clearExpired();
            LOG.info("third step: clear expire data at fileUpLogCacheMap,success:" +
                    expireCount + ",fileUpLogCacheMap size:" + UpFileInstance.getInstance().getSize());
            LOG.info("job END.....");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * read the s3 failed log
     *
     * @param descPath
     */
    public static void againStoreS3(String descPath) {
        LOG.info("read the amazon s3 failed file log:" + descPath);
        String fileContent = FileStoreUtil.read(descPath);
        if (StringUtils.isEmpty(fileContent)) {
            return;
        }
        String[] fileObjArr = fileContent.split("\n");
        int failedCount = 0;
        if (fileObjArr != null) {
            for (String fileObj : fileObjArr) {
                FileDTO fileDTO = (FileDTO) JsonParser.jsonStrToObj(fileObj, FileDTO.class);
                if (fileDTO != null) {
                    fileDTO.setDelFlag(1);
                    StoreFilePool.getThreadPool().add(fileDTO);
                    failedCount++;
                }
            }
        }
        LOG.info("END step...,read file count:" + failedCount);
    }

    /**
     * clear the tmp Dir
     */
    public static void clearTempFile(File tmpFileDir) {
        if (!tmpFileDir.isDirectory()) {
            return;
        }

        for (File file : tmpFileDir.listFiles()) {
            if (file.isDirectory()) {
                clearTempFile(file);
            }

            if (isDel(file)) {
                boolean result = file.delete();
                if (!result) {
                    LOG.error("Fail to delete temp file" + file.getName());
                }
            }

        }
    }


    /**
     * modifed time > one day
     *
     * @param file
     * @return
     */
    private static boolean isDel(File file) {
        long currentTimeMillis = System.currentTimeMillis();
        long lastModifiedTimsMillis = file.lastModified();
        if (currentTimeMillis - lastModifiedTimsMillis > Constants.Common.INTERVAL_TIME) {
            return true;
        }
        return false;
    }
}
